package com.example.bigworkdemo.web.controller;

import com.example.bigworkdemo.bean.user;
import com.example.bigworkdemo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/api")
public class userManage {
    @Autowired
    private userService userService;
    @GetMapping("/user/{id}")
    public String getUserInfoById(@PathVariable Integer id, Model m){
       user u = userService.findUserByid(id);
       if(u!=null){
           m.addAttribute("msg","查询成功");
           m.addAttribute("user",u);
           return "success";
       }
     else {
           m.addAttribute("msg","查不到此用户");
           return "fault";
       }
    }
    @PostMapping("/user")
    public String addUser(user u,Model m){
      int r =  userService.addUser(u);
      if(r==1){
          m.addAttribute("msg","添加用户成功!");
          return "success";
      }
        m.addAttribute("msg","添加用户失败!");
      return "fault";
    }
    @PutMapping("/user")
    @ResponseBody
    public String changeUser(user u){
        System.out.println(u);
        int r =  userService.changeUser(u);
        if(r==1){
            return "修改用户成功！";
        }
        return "修改用户失败!不存在此用户";
    }
    @RequestMapping(value = "/user/{userId}",method = RequestMethod.DELETE,produces = "application/text;charset=utf-8")
    @ResponseBody
    public String delete(@PathVariable Integer userId){
        int r =  userService.delete(userId);
        if(r == 1){
            return "删除成功！";
        }
        else {

            return "删除失败，不存在此用户";
        }
    }
    @GetMapping("/user/all")
    public String getAllUser(Model m){
        List<user> userList = userService.getUserList() ;
        m.addAttribute("userList",userList);
         return "userList";
    }
}
